// cloudfunctions/co-user/controller/user.controller.js
const ApiResponse = require('../common/api-response.js')

class UserController {
  constructor(cloudObject) {
    this.db = uniCloud.database()
    this.userCollection = this.db.collection('uni-id-users')
	this.cloudObject = cloudObject
  }
  
  // 返回从token中获得的信息
  // {"code":0,"errCode":0,"uid":"67e749453ad13a79775be463","role":["wallpaper-admin"],"permission":["wcr","wca","wce","wcd","wdr","wda","wde","wdd","wir","wia","wie","wid"],"iat":1744179237,"exp":1744186437}
  async getUserInfo() {
	  const cloudOBJ = this.cloudObject
	  if (!cloudOBJ.uniIdToken) {
	        throw new Error('TOKEN_INVALID')
	}
	  
	  const res = await cloudOBJ.uniID.checkToken(cloudOBJ.uniIdToken)
	  if (res.code) {
		throw new Error(res.message || 'TOKEN_INVALID')
	  }
	  this.userInfo = {}
	  // 其中包括：uid,role,permission
	  this.userInfo.uid = res.uid || ''
	  this.userInfo.role = res.role || []
	  this.userInfo.permission = res.permission || []
	  this.userInfo.iat = res.iat || Date.now()
	  this.userInfo.exp = res.exp || Date.now()
	  if(this.exp*1000 <= Date.now()) {
		  throw new Error('TOKEN_EXPIRED') 
	  }
	  return res
  }
  
/**
 * 判断当前用户是否有对应权限或角色
 * @param {string|array} value - 需要检查的权限标识或角色
 * @param {string} [option='include'] - 校验方法，'allin'：必须包含所有；'onein': 包含任意一个即可
 * @param {string} [checkType='permission'] - 检查类型，'permission'或'role'
 * @returns {boolean} 有无权限/角色
 */
async hasPermission(value, option = 'allin', checkType = 'permission') {
  if (!this.userInfo || !this.userInfo.uid) {
    // 说明未执行了getUserInfo()方法
    await this.getUserInfo();
  }
  
  // 如果用户是admin角色，直接返回true，拥有所有权限
if (this.userInfo.role && this.userInfo.role.includes('admin')) {
  return true;
}

  // 确定要检查的字段
  const checkField = checkType === 'role' ? 'role' : 'permission';

  
  // 如果用户没有对应的权限/角色字段或为空，直接返回false
  if (!this.userInfo[checkField] || !this.userInfo[checkField].length) {
    return false;
  }

  // 统一处理value参数，确保是数组形式
  const valuesToCheck = Array.isArray(value) ? value : [value];
  let re = false
  if(option == 'onein') {
	  re = valuesToCheck.some(val => 
        this.userInfo[checkField].includes(val)
      )
  } else {
	 re = valuesToCheck.every(val =>
	    this.userInfo[checkField].includes(val)
	  )
  }

  if(!re) throw new Error(`${value} ${option} ${checkType} 权限校验失败`)
  return true
}

  /**
   * 获取用户信息
   * @param {string} uid - 用户ID
   * @returns {Promise<ApiResponse>} 统一响应格式
   */
  async getUserInfoDBDetal(uid) {
      if (!uid) {
        throw new Error('用户id为空')
      }
      const res = await this.userCollection.doc(uid).get()
      if (res.data && res.data.length > 0) {
        const userInfo = res.data[0]
        // 过滤敏感信息
        const { password, token, token_expired, ...safeInfo } = userInfo
        
        return safeInfo
      } else {
		  throw new Error('没有找到对应用户信息')
	  }
  }
}

module.exports = UserController